package com.fc.mall.portal.service.impl;

import com.fc.mall.mapper.*;
import com.fc.mall.model.*;
import com.fc.mall.mapper.PmsMemberPriceMapper;
import com.fc.mall.mapper.PmsProductAttributeMapper;
import com.fc.mall.mapper.PmsProductAttributeValueMapper;
import com.fc.mall.mapper.PmsProductMapper;
import com.fc.mall.portal.dao.PortalProductDao;
import com.fc.mall.portal.dao.UmsMemberLevelDao;
import com.fc.mall.portal.domain.ProductQueryParam;
import com.fc.mall.portal.domain.PromotionProduct;
import com.fc.mall.portal.service.*;
import com.fc.mall.portal.vo.PmsProductAttrVO;
import com.fc.mall.portal.vo.PmsProductVO;
import com.fc.mall.util.Constants;
import com.fc.mall.model.*;
import com.fc.mall.portal.service.*;
import com.github.pagehelper.PageHelper;
import ma.glasnost.orika.MapperFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 商品管理Service实现类
 * Created by dobuy on 2018/4/26.
 */
@Service
public class ProductServiceImpl implements ProductService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ProductServiceImpl.class);

    @Autowired
    private PmsProductMapper productMapper;

    @Autowired
    private PortalProductDao portalProductDao;

    @Autowired
    MapperFacade mapperFacade;

    @Autowired
    private PmsProductAttributeMapper pmsProductAttributeMapper;

    @Autowired
    private PmsProductAttributeValueMapper pmsProductAttributeValueMapper;

    @Autowired
    private OmsPromotionService omsPromotionService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private UmsMemberService memberService;

    @Autowired
    private UmsMemberLevelDao umsMemberLevelDao;

    @Autowired
    private PmsMemberPriceMapper memberPriceMapper;

    @Autowired
    private SkuStockService skuStockService;

    @Override
    public PmsProductVO getInfo(Long id) {
        PmsProduct pmsProduct = productMapper.selectByPrimaryKey(id);
        PmsProductVO pmsProductVO = mapperFacade.map(pmsProduct, PmsProductVO.class);
        PmsProductAttributeValueExample pmsProductAttributeValueExample = new PmsProductAttributeValueExample();
        PmsProductAttributeValueExample.Criteria attrValueCriteria = pmsProductAttributeValueExample.createCriteria();
        attrValueCriteria.andProductIdEqualTo(id);
        List<PmsProductAttributeValue> pmsProductAttributeValueList = pmsProductAttributeValueMapper.selectByExample(pmsProductAttributeValueExample);

        List<PmsProductAttrVO> attrVOList = new ArrayList<>();
        for (PmsProductAttributeValue attrVal : pmsProductAttributeValueList) {
            PmsProductAttribute pmsAttr = pmsProductAttributeMapper.selectByPrimaryKey(attrVal.getProductAttributeId());
            PmsProductAttrVO pmsProductAttrVO = mapperFacade.map(pmsAttr, PmsProductAttrVO.class);
            pmsProductAttrVO.setValue(attrVal.getValue());
            pmsProductAttrVO.setProductId(attrVal.getProductId());
            attrVOList.add(pmsProductAttrVO);
        }
        pmsProductVO.setAttrVOList(attrVOList);
        //促销
        calculatePromotionPrice(pmsProductVO);

        // 根据登录则的角色（代理商 or 合伙人）计算下级会员购买该产品时得到的分佣金额，单位 分
        pmsProductVO.setCommissionAccount(calculateCommissionAccountByLevelType(pmsProductVO.getPrice(), pmsProductVO.getCommissionRate()));
        pmsProductVO.setPromotionMessages(calculatePromotionMsg(pmsProduct));
        return pmsProductVO;
    }

    /**
     *  整合优惠价格
     */

    private void calculatePromotionPrice(PmsProductVO pmsProduct)
    {
        if(pmsProduct.getPromotionType().intValue() == 1)
        {
            if(pmsProduct.getPromotionEndTime().before(new Date()))
            {
                pmsProduct.setPromotionType(0);
            } else if (pmsProduct.getPromotionPrice().intValue() >0) {
                pmsProduct.setOriginalPrice(pmsProduct.getPrice());
                pmsProduct.setPrice(pmsProduct.getPrice().multiply(pmsProduct.getPromotionPrice()).divide(new BigDecimal(100)).setScale(2));
            }
        }
        else if(pmsProduct.getPromotionType().intValue() == 2)
        {
            UmsMember currentMember = memberService.getCurrentMember();
            if(null == currentMember)
            {
                return;
            }
            BigDecimal originalPrice = pmsProduct.getPrice();

            PmsMemberPriceExample example = new PmsMemberPriceExample();
            example.createCriteria().andProductIdEqualTo(pmsProduct.getId()).andMemberLevelIdEqualTo(currentMember.getMemberLevelId());
            List<PmsMemberPrice> pmsMemberPriceList = memberPriceMapper.selectByExample(example);
            if(pmsMemberPriceList != null && !pmsMemberPriceList.isEmpty())
            {
                PmsMemberPrice pmsMemberPrice = pmsMemberPriceList.get(0);
                if(null != pmsMemberPrice.getMemberPrice())
                {
                    pmsProduct.setPrice(originalPrice.multiply(pmsMemberPrice.getMemberPrice()).divide(new BigDecimal(100)).setScale(2));
                    pmsProduct.setOriginalPrice(originalPrice);
                } else {
                    pmsProduct.setPromotionType(0);
                }
            }

        }
    }
    /**
     * 整合优惠消息
     * @param pmsProduct
     * @return
     */
    private List<String> calculatePromotionMsg(PmsProduct pmsProduct)
    {
        List<String> promotionMsg = new ArrayList<>();
        if (pmsProduct.getPromotionType().intValue() == 0)
        {
            return promotionMsg;
        }
        PromotionProduct promotionProduct = queryByProductId(pmsProduct.getId());
        if(null == promotionProduct)
        {
            return promotionMsg;
        }
        if (pmsProduct.getPromotionType().intValue() == 1)
        {
            promotionMsg.add("限时促销");
        }
        if (pmsProduct.getPromotionType().intValue() == 2)
        {
            promotionMsg.add("会员优惠");
        }
        if (pmsProduct.getPromotionType().intValue() == 3)
        {
            List<PmsProductLadder> ladders = promotionProduct.getProductLadderList();
            if(!ladders.isEmpty())
            {
                ladders.forEach(ladder -> {
                    StringBuilder sb = new StringBuilder();
                    sb.append("满");
                    sb.append(ladder.getCount());
                    sb.append("件，");
                    sb.append("打");
                    if(ladder.getDiscount().intValue() < 10) {
                        sb.append(ladder.getDiscount().divide(new BigDecimal(10)).setScale(1));
                    }
                    else if(ladder.getDiscount().intValue() % 10 == 0)
                    {
                        sb.append(ladder.getDiscount().divide(new BigDecimal(10)).setScale(0));
                    }
                    else
                    {
                        sb.append(ladder.getDiscount().setScale(0));
                    }

                    sb.append("折");
                    promotionMsg.add(sb.toString());
                });

            }
        }

        if (pmsProduct.getPromotionType().intValue() == 4)
        {
            List<PmsProductFullReduction> fullReductions = promotionProduct.getProductFullReductionList();
            if(!fullReductions.isEmpty())
            {
                fullReductions.forEach(fullReduction -> {
                    StringBuilder sb = new StringBuilder();
                    sb.append("满");
                    sb.append(fullReduction.getFullPrice().setScale(0));
                    sb.append("减");
                    sb.append(fullReduction.getReducePrice().setScale(0));
                    promotionMsg.add(sb.toString());
                });
            }
        }
        return promotionMsg;
    }
    /**
     * 通过用户等级类型获取计算下级购买该商品所获得的分佣金额
     * @param promotionPrice
     * @param commissionRate
     * @return
     */
    private Integer calculateCommissionAccountByLevelType(BigDecimal promotionPrice, Integer commissionRate)
    {
        if(promotionPrice == null
                || commissionRate == null
                || commissionRate == 0)
        {
            return 0;
        }

        UmsMember currentMember = memberService.getCurrentMember();
        if(currentMember.getLevelType().intValue() == Constants.MemberLevelType.Partner.getValue()) {
            return promotionPrice.multiply(new BigDecimal(100)).intValue() * commissionRate/100;
        }

        UmsMemberLevel memberLevel = umsMemberLevelDao.getMemberLevelByMemberId(currentMember.getId());
        if(null == memberLevel || memberLevel.getCommissionFirstRate().equals(0))
        {
            return  0;
        }

        Integer refererRate = memberLevel.getCommissionFirstRate();
        //（商品销售价格 * 100 * 分佣比例%）  * 会员当前等级类型的分佣比例%
        return (promotionPrice.multiply(new BigDecimal(100)).intValue() * refererRate / 100) * commissionRate / 100;
    }

    /**
     *
     */
    @Override
    public List<PmsProductVO> list(ProductQueryParam productQueryParam, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        PmsProductExample productExample = new PmsProductExample();
        PmsProductExample.Criteria criteria = productExample.createCriteria();
        criteria.andDeleteStatusEqualTo(0);
        if (productQueryParam.getPublishStatus() != null) {
            criteria.andPublishStatusEqualTo(productQueryParam.getPublishStatus());
        }
        if (productQueryParam.getVerifyStatus() != null) {
            criteria.andVerifyStatusEqualTo(productQueryParam.getVerifyStatus());
        }
        if (!StringUtils.isEmpty(productQueryParam.getKeyword())) {
            criteria.andNameLike("%" + productQueryParam.getKeyword() + "%");
        }
        if (!StringUtils.isEmpty(productQueryParam.getProductSn())) {
            criteria.andProductSnEqualTo(productQueryParam.getProductSn());
        }
        if (productQueryParam.getBrandId() != null) {
            criteria.andBrandIdEqualTo(productQueryParam.getBrandId());
        }
        if (productQueryParam.getProductCategoryId() != null) {
            criteria.andCategoryIdsLike(productQueryParam.getProductCategoryId().toString());
        }

        //设置排序
        if (ProductQueryParam.sortMap.get(productQueryParam.getSort()) != null
                && ProductQueryParam.orderMap.get(productQueryParam.getOrder()) != null) {
            String sortVal = ProductQueryParam.sortMap.get(productQueryParam.getSort());
            String orderVal = ProductQueryParam.orderMap.get(productQueryParam.getOrder());
            productExample.setOrderByClause(sortVal + " " + orderVal);
        }

        List<PmsProductVO> productList = portalProductDao.selectProductVOList(productExample);
        productList.forEach(prod -> {
            calculatePromotionPrice(prod);
            prod.setCommissionAccount(calculateCommissionAccountByLevelType(prod.getPrice(), prod.getCommissionRate()));
        });
        return productList;
    }

    @Override
    public List<PmsProduct> list(String keyword) {
        PmsProductExample productExample = new PmsProductExample();
       //todo:
        return productMapper.selectByExample(productExample);
    }

    @Override
    public PromotionProduct queryByProductId(Long id) {
        List<Long> productIds = new ArrayList<>();
        productIds.add(id);
        List<PromotionProduct> promotionProducts = portalProductDao.getPromotionProductList(productIds);
        if(promotionProducts.isEmpty())
        {
            return null;
        }
        return promotionProducts.get(0);
    }

}
